template.defaults.imports.CountdownTime = function (factEndDate) {
    var timestamp = (new Date()).valueOf();
    return factEndDate - timestamp;
};

template.defaults.imports.TimestampToTime = function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    return Y + M + D + h + m ;
};

//下拉刷新
$("#tab1").pullToRefresh().on("pull-to-refresh", function () {
    $("#weipai-list-content .left-list").html("");
    $("#weipai-list-content .right-list").html("");
    resetCondition();
    queryList(function () {
        $("#weipai").pullToRefreshDone(); // 重置下拉刷新
    });
    return false;
});

//上拉加载更多
$('#tab1').infinite().on("infinite", function () {
    if (hasNextPage) {
        pageNo++;
        queryList(function () {}, true);
    }
});

//通过token获得shopId,再通过shopId查询店铺基本信息
$.ajaxSettings.async = false;
var shopId = '';
$.post('/antique/api/sysUser/query_my_info', {
    token: getCookie('token')
}, function (result) {
    var data = result.data;
    $.ajaxSettings.async = false;
    shopId = data.shopDetail.id;
});

$.get('/antique/api/mallShop/web/query', {
    id:shopId
}, function (result) {
    var html = template('sdetail', result);
    document.getElementById('sdetail-content').innerHTML = html;

    //增加店铺的推荐时间
    $('#add-recommend-shop').click(function(){
        $('#recommend-shop').popup();
        $('#recommend-shop .weui-cells .items .item').click(function(){
            $('.weui-popup__container .weui-cells .items .item').removeClass('selected');
            $(this).addClass('selected');
        });

        $('#confirmRecommendShop').unbind('click').bind('click',function(){
            var day = $('#recommend-shop .weui-cells .items .selected').data('day');
            $.post('/antique/api/mallShop/manage/recommend_adv_show',{
                token:getCookie('token'),
                id:shopId,
                days:day
            },function(result){
                if (result.code == 0) {
                    $("#recommend-shop .weui-cells .items .item").removeClass('selected');
                    //弹起支付框
                    //设置支付金额
                    $('.total_pay').text(result.data.needMoney);
                    $("#pay_price").popup();

                    $('#confirmPricePay').unbind('click').bind('click',function(){
                        var type = $("#pay_price input[name='fastRadioPay']:checked").val();
                        setPricePay(result.data.needMoney,result.data.advShowId,type,152);
                    });
                } else {
                    $.toast(result.message, "cancel");
                }
            });
            return false;
        });
        return false;
    });
});

//查看已热推藏品
$.post('/antique/api/mallProduct/web/query_list',{
    queryType:5,
    shopId:shopId,
    start:0,
    limit:20
},function(result){
    $('#products-content').append(template('products-list', {
        list:result.data.list
    }));
});

$('.chat').click(function(){
    visitUrl('/chat?charToUser=gjzx_service',true);
});

$('.tel').click(function(){
    window.location.href = "tel:023-60333183";
});

//复位所有参数
/* global cate1 resetCate cate2 attrs*/
function resetCondition() {
    pageNo = 1;
}

var loading = false; //状态标记
var hasNextPage = false;
var pageNo = 1;
queryList();
function queryList(callback, isMore) {
    if (loading) return;
    loading = true;
    
    $.post('/antique/api/mallProduct/web/query_list', {
        queryType:6,
        shopId:shopId,
        start:0,
        limit:50
    }, function (result) {
        $('#no-recommend-content').append(template('no-recommend-list', {
            list:result.data.list
        }));
        hasNextPage = result.data.hasNextPage;
        if (!result.data.hasNextPage) {
            $('#loadmore').hide();
            $('#nomore').show();
        } else {
            $('#loadmore').show();
            $('#nomore').hide();
        }
        if (callback) callback();
        loading = false;

        //推荐藏品
        $('.products .container .item .row button').unbind('click').bind('click',function(){
            var id = $(this).data('id');
            $("#recommend-antique").popup();
            $('#recommend-antique .weui-cells .items .item').click(function(){
                $('.weui-popup__container .weui-cells .items .item').removeClass('selected');
                $(this).addClass('selected');
            });

            $('#confirmRecommend').unbind('click').bind('click',function(){
                var day = $('#recommend-antique .weui-cells .items .selected').data('day');
                $.post('/antique/api/mallProduct/manage/recommend_adv_show',{
                    token:getCookie('token'),
                    id:id,
                    days:day
                },function(result){
                    if (result.code == 0) {
                        $("#recommend-antique .weui-cells .items .item").removeClass('selected');
                        //弹起支付框
                        //设置支付金额
                        $('.total_pay').text(result.data.needMoney);
                        $("#pay_price").popup();

                        $('#confirmPricePay').unbind('click').bind('click',function(){
                            var type = $("#pay_price input[name='fastRadioPay']:checked").val();
                            setPricePay(result.data.needMoney,result.data.advShowId,type,151);
                        });
                    } else {
                        $.toast(result.message, "cancel");
                    }
                });
                return false;
            });
            return false;
        });
    });
}

$.post('/antique/api/mallShop/manage/query_myshop',{
    token:getCookie('token')
},function(result){
    if(result.data.advShow){
        //如果有广告的话
        var dateStr = timestampToDate(result.data.advShowEndDate);
        $('#shopRecommendEndDate').text('推荐' + dateStr + '后到期');
    } else {
        
    }
});

//确认一口价支付
function setPricePay(money,advShowId,type,payType){
    //等于1为钱包支付，等于2为微信支付
    /* global hex_md5 isMiniProgram wx*/
    if (type == 1){
        passwordPay(advShowId,payType);
    } else if (type == 2){
        if ( isMiniProgram () ) {//小程序就跳转小程序支付
            var params = {
                type: payType,//支付类型
                id: advShowId,//关联id
                payMoney: money,//支付金额
                content:'购买推荐广告花费' + money + '.00元',//订单说明
                jumpUrl:'/pages/auctionCollectDetail',//支付成功后跳转地址  为空返回当前页面 不可以带 ? 和 &
            };
            wx.miniProgram.navigateTo({
                url: "/pages/pay/index?params=" + JSON.stringify(params)
            });
        } else {
            /* global getCookie servicePay*/
            $.post('/antique/api/onlinePay/wxpay/create_wxpay', {
                token:getCookie('token'),
                type:payType,
                appSource:1,
                keyId:advShowId,
                money:servicePay(money),
                content:'购买推荐广告花费' + money + '.00元'
            }, function (result) {
                var appId = result.data.appid;
                var nonceStr = result.data.nonce_str;
                var prepay_id = result.data.prepay_id;
                var mch_id = result.data.mch_id;
                /* global goWeiPay */
                goWeiPay(appId,nonceStr,prepay_id,mch_id);
            });
        }
    }
}

function passwordPay(id,payType) {
    /* global havePayPwd */
    havePayPwd (function(havePwd) {
        if (havePwd) {
            $.modal({
                title: "请输入支付密码",
                text: '<input class="weui-input weui-prompt-input" type="password" id="password"  placeholder="没有设置密码可不填" />',
                buttons: [{
                        text: "取消",
                        className: "default"
                    },
                    {
                        text: "确定",
                        onClick: function () {
                            var password = $("#password").val();
                            var params = {};
                            params.id = id;
                            params.payType = payType;
                            params.token = getCookie('token');
                            var time = timeToTimestamp(new Date());
                            if (password == '') {
                                params.payPass = hex_md5(time + '').toUpperCase();
                            } else {
                                var passwords = hex_md5(password).toUpperCase();
                                params.payPass = hex_md5(passwords + time).toUpperCase();
                            }
                            params.time = time;
                            submitAdd(params);
                        }
                    }
                ]
            });
        } else {
            var password = '';
            var params = {};
            params.id = id;
            params.payType = payType;
            params.token = getCookie('token');
            var time = timeToTimestamp(new Date());
            if (password == '') {
                params.payPass = hex_md5(time + '').toUpperCase();
            } else {
                var passwords = hex_md5(password).toUpperCase();
                params.payPass = hex_md5(passwords + time).toUpperCase();
            }
            params.time = time;
            submitAdd(params);
        }
    });
}

/** 提交支付密码进行保证金支付 */
function submitAdd(params){
    if(params.payType == 151){
        //藏品
        $.ajax({
            type:'POST',
            url:"/antique/api/mallProduct/manage/recommend_adv_show_pay",
            data: params,
            dataType:"json",
            success:function(res){
                if (res.code == 0){
                   // window.location.href = document.referrer;
                    $.toast("支付成功!");
                    window.location.reload();
                 } else {
                    $.toast(res.message, "cancel");
                }            
            }
        });
    } else if(params.payType == 152){
        //店铺
        $.ajax({
            type:'POST',
            url:"/antique/api/mallShop/manage/recommend_adv_show_pay",
            data: params,
            dataType:"json",
            success:function(res){
                if (res.code == 0){
                   // window.location.href = document.referrer;
                    $.toast("支付成功!");
                    window.location.reload();
                 } else {
                    $.toast(res.message, "cancel");
                }
            }
        });
    }    
}